---------------------------------------------------------------
-- @Copyright：           zour
-- @Description：         调用账号服的接口函数

-- @modify time           2021-09-27
---------------------------------------------------------------
require "modules.business_advert.advert_define"

local FOO = {
	_VERSION = '0.1.0',

	__INT32__  = 2147483648;
	__UINT32__ = 4294967296;
}

--===================================local function=====================================
local function call_account(url_, params_)
	--log.debug( "call_account url=" .. url_ )
	local url_str_ = ""
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&'
	end

	local md5_seed_ = uu.getStringBySortKey( params_ ) .. '522e6ccde68f4584a3282ce0b0eca1cf'

	local url_all_ = url_ .. '?' .. url_str_ .. 'sign=' .. ngx.md5( md5_seed_ )

	local ret, body = ns_network.getHttpPage( url_all_ )
	--log.debug("ret="..ret)
	--log.debug("body="..serpent.block(body))

	if  ret == 200 then
		return uu.json2table( body )
	else
		return {}
	end
end

local function call_ma_server(url_, params_, time_)
	log.debug( "call_ma_server url=" .. url_ )
	local url_str_ = ""
	local is_cmd = false
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&'
		if k=="cmd" then 
			is_cmd = true
		end
	end

	local n_uin = ngx.ctx.m_params.uin
	local n_ts = time_
	local s_auth = ngx.md5(n_ts .. '#miniw_907#' .. n_uin)
	local s_md5 = ngx.md5(n_ts .. '#_php_miniw_2016_#' .. n_uin)
	local url_all_ = url_ .. '?' .. url_str_ 
	if is_cmd then 
		url_all_ = url_all_ .. 'auth=' .. s_auth
	else
		url_all_ = url_all_ .. 'md5=' .. s_md5
	end

	local ret, body = ns_network.getHttpPage( url_all_ )
	if  ret == 200 then
		return uu.safe_loadstring( body )
	else
		return {}
	end
end

local function call_business_server(url_, params_, time_)
	log.debug( "call_business_server url=" .. url_ )
	local url_str_ = ""
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&'
	end

	local n_uin = ngx.ctx.m_params.uin
	local n_ts = time_
	local s_md5 = ngx.md5(n_ts .. '#_php_miniw_2016_#' .. n_uin)
	local url_all_ = url_ .. '?' .. url_str_ 
	url_all_ = url_all_ .. 'md5=' .. s_md5

	local ret, body = ns_network.getHttpPage( url_all_ )
	if  ret == 200 then
		return uu.safe_loadstring( body )
	else
		return {}
	end
end


-------------------------------------------------------------
local function pack_base_str(request_list, param_list, code_fun)
	local base_str = false
	for i=1, #param_list do
		local key   = param_list[i]
		local value = request_list[key]
		if value then
			local code_value = value
			if code_fun then
				code_value = ngx.escape_uri(value)
			end

			if not base_str then
				base_str = key .. "=" .. code_value
			else
				base_str = base_str .. "&" .. key .. "=" .. code_value
			end
		else
			log.error(string.format("key not exist:[key=%s]", key))
			return false
		end
	end

	return base_str
end

local function make_md5(request_list, param_list, private_key)
	table.sort(param_list, function(left, right) if left < right then return true end end)

	local base_str = pack_base_str(request_list, param_list)
	if not base_str then
		return false
	end

	local auth_md5 = ngx.md5(base_str .. private_key)
	return auth_md5
end

local function call_business_welfare_server(url_, params_)
	log.debug( "call_business_welfare_server url=" .. url_ )
	local check_md5_param_old = {
		act = 1,
		time = 1,
		apiid = 1,
		ver = 1,
		uin = 1,
		type = 1,
		num = 1,
		buy_times = 1,
		times = 1,
		gift_id = 1,
		s2t = 1,
		buy_id = 1,
	}
	local private_key = "3dbc5f33add11d1af78ba2af365e0952"
	local param_list = {}
    for k, _ in pairs(params_ or {}) do
        if check_md5_param_old[k] then
            table.insert(param_list, k)
        end
    end

	--log.debug("ngx.ctx.m_params=".. serpent.block(params_))
	--log.debug("param_list=".. serpent.block(param_list))
	-- 验证签名
	local auth_md5 = make_md5(params_, param_list, private_key)
	local url_str_ = ""
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&'
	end
	local url_all_ = url_ .. '?' .. url_str_ 
	url_all_ = url_all_ .. 'md5=' .. auth_md5

	local ret, body = ns_network.getHttpPage( url_all_ )
	if  ret == 200 then
		return uu.safe_loadstring( body )
	else
		return {}
	end
end

local function call_battlepass( url_, params_, time_ )
	log.debug( "call_battlepass_server url=" .. url_ )
	local url_str_ = ""
	for k, v in pairs(params_) do
		url_str_ = url_str_ .. k .. '=' .. ngx.escape_uri(v) .. '&'
	end

	local n_uin = ngx.ctx.m_params.uin
	local n_ts = time_
	local s_md5 = ngx.md5(n_ts .. '#_php_miniw_2016_#' .. n_uin)
	local url_all_ = url_ .. '?' .. url_str_ 
	url_all_ = url_all_ .. 'md5=' .. s_md5

	local ret, body = ns_network.getHttpPage( url_all_ )
	if  ret == 200 then
		return uu.safe_loadstring( body )
	else
		return {}
	end
end

--===================================api function=====================================
--测试调用账号服接口
--[[
FOO.test_account_api = function()
	--获取所有物品
	local ret, result = FOO.get_all_items()
	if ret then 
		log.debug("-------------------test_account_api get_all_items ok!")
		uu.var_dump(result)
	end
	--查看迷你点抽奖券数量
	local ret, result = FOO.get_item_nums(10054)
	if ret then 
		log.debug("-------------------test_account_api get_item_nums ok! nums= "..result)
	end
	--增加迷你点抽奖券数量
	local items = {
		{id=10054, num=1}
	}
	local ret = FOO.items_add(items)
	if ret then 
		local ret, result = FOO.get_item_nums(10054)
		log.debug("-------------------test_account_api items_add ok!  nums= "..result)
	end
	--增加迷你点抽奖券数量
	local ret = FOO.item_reduce(10054, 1)
	if ret then 
		local ret, result = FOO.get_item_nums(10054)
		log.debug("-------------------test_account_api item_reduce ok!  nums= "..result)
	end
end
--]]

--! @账号服中转数据
FOO.order_send_account = function(uin, order_id)
	local uin_ = tonumber(uin) or 0
	local reason_ = reason_ or "business_advert_transfer"
	local info = {
		uin = uin_,
		cmd = 'dev_ad_add_item_by_order',
		order_id = order_id,
		ts = uu.now(),
	 }
	local ret = call_account( ns_config.gm_cost_server_url[ (ngx.ctx.m_params.uin  % #ns_config.gm_cost_server_url) + 1 ],info)
	if ret.return_code == 'SUCCESS' then
		log.day_list(ADVERT_REWARDS, "order_send_account",ngx.ctx.m_params.uin,order_id,reason_,uu.table2json(ret.return_code), uu.now(), uu.to_str(ret))
		return true
	else
		log.day_list(ADVERT_REWARDS, "order_send_account",ngx.ctx.m_params.uin,order_id,reason_,uu.table2json(ret.return_code), uu.now(), uu.to_str(ret))
		return false
	end
end


--! @brief 减少物品
FOO.item_reduce = function(itemid, num, reason_)
	local itemid_ = tonumber(itemid)
	local num_ = tonumber(num) or 0
	local reason_ = reason_ or "business_advert_finish"
	local info = {
		cmd = 'item_rm',
		id = itemid_,
		num = num_, 
		reason = reason_,
		uin = ngx.ctx.m_params.uin,
		ts = uu.now(),
	 }
	local ret = call_account( ns_config.gm_cost_server_url[ (ngx.ctx.m_params.uin  % #ns_config.gm_cost_server_url) + 1 ],info)
	if ret.return_code == 'SUCCESS' then
		log.day_list(ADVERT_REWARDS, "item_remove",ngx.ctx.m_params.uin,itemid, num,reason_,uu.table2json(ret.return_code), uu.now())
		return true
	else
		log.day_list(ADVERT_REWARDS, "item_remove",ngx.ctx.m_params.uin,itemid, num,reason_,uu.table2json(ret.return_code), uu.now())
		return false
	end
end


--! @brief 增加物品 items: {{id=xx,num=xx},{id=xx,num=xx},...}
FOO.items_add = function(items, position_id, reason_)
	local new_items = {}
	for _, item in pairs(items) do 
		local id = tonumber(item.id) or 0
		local num = tonumber(item.num) or 0
		if id and id > 0 and num and num > 0 then 
			new_items[#new_items+1] = {id=id, num=num}
		else
			log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .."]  items_add"), "id or num is nil", ngx.ctx.m_params.uin, reason_, id,num)
		end
	end
	local reasons =  reason_ or 'business_advert_finish'
	local json_item = uu.table2json(new_items)
	local info = {
		cmd ='items_add', 
		items = json_item, 
		reason = reasons,
		uin = ngx.ctx.m_params.uin,
		ts = uu.now(),
		ApiID = ngx.ctx.m_params.apiid, 
		platform_id = ngx.ctx.m_params.platform_id,
		position_id = position_id, 
		CltVersion =  ngx.ctx.m_params.CltVersion,
		client_ip = ngx.ctx.m_params.client_ip or ngx.ctx.xff,
	}
	local ret = call_account( ns_config.gm_cost_server_url[ (ngx.ctx.m_params.uin % #ns_config.gm_cost_server_url) + 1 ],info)
	if ret.return_code == 'SUCCESS' then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .."] items_add") ,"success",ngx.ctx.m_params.uin,reasons,json_item,uu.table2json(ret),uu.now())
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .."] items_add"),"fail",ngx.ctx.m_params.uin,reasons,json_item,uu.table2json(ret),uu.now())
	end
	return ret
end

--! @brief 获取账号服物品信息
FOO.get_all_items = function(uin)
	uin = uin or ngx.ctx.m_params.uin
	--net
	local tmp_ = {
		cmd      = "query",
		path     = "Account.ItemInfo",
		uin      = uin or 0,
		ts       = uu.now(),
		-- ignore   = 1,
	};
	local ret_ = call_account( ns_config.gm_cost_server_url[ (uin % #ns_config.gm_cost_server_url) + 1 ], tmp_ );
	if ret_.return_code and ret_.return_code=='SUCCESS' then
		return true, ret_.return_result or {};
	else
		log.day_list(ADVERT_REWARDS, 'account', "get_account_items_info fail", uin, uu.to_str(ret_) );
		return false;
	end
end

--! @brief 获取账号服某个道具数量
FOO.get_item_nums = function(id, uin)
	uin = tonumber(uin) or tonumber(ngx.ctx.m_params.uin)
	id = tonumber(id) or 0
	if uin <= 0 or id <= 0 then 
		log.day_list(ADVERT_REWARDS, "account", "get_account_item_num fail. uin or id is nil", uin, id);
		return false
	end
	local ret, v = FOO.get_all_items(uin)
	if not ret then 
		log.day_list(ADVERT_REWARDS, "account", "get_account_item_num fail", uin, id, uu.to_str(ret) );
		return false
	end
	-- [3]={["Num"]=1026,["ItemID"]=20032}
	if v['Account.ItemInfo'] then 
		for _, item in ipairs(v['Account.ItemInfo']) do
			if item.ItemID == id then 
				return true, item.Num
			end
		end
	end
	return true, 0
end

--! @brief 减果实冷却时间
FOO.fruittime_rm = function(fruitIndex_, reduce_time_, position_id)
	local reason_ = 'business_advert_reduce_fruit_time'
	local info = {
		cmd = 'fruittime_rm',
		fruitIndex =  tonumber(fruitIndex_) ,
		stime = tonumber(reduce_time_), 
		reason =  reason_,
		uin = ngx.ctx.m_params.uin,
		ts = uu.now(),
	 }
	local ret = call_account( ns_config.gm_cost_server_url[ (ngx.ctx.m_params.uin  % #ns_config.gm_cost_server_url) + 1 ], info)
	if ret.return_code == 'SUCCESS' then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] fruittime_rm SUCCESS"), ngx.ctx.m_params.uin,fruitIndex_, reduce_time_, reason_, uu.table2json(ret.return_code), uu.now())
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] fruittime_rm FAILURE"), ngx.ctx.m_params.uin,fruitIndex_, reduce_time_, reason_, uu.table2json(ret.return_code), uu.now())
	end

	return ret
end

--! @brief 分享次数奖励
FOO.set_share_win_bean_data = function(extra_t, position_id)
	local reason_ = 'business_advert_set_share_win_bean_data'
	local time_ = uu.now()
	local info = {
		act = 'set_share_win_bean_data',
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver or "1.6.0",
		apiid = ngx.ctx.m_params.apiid or 999,
		flag = extra_t.flag or 2,
	}

	local ret = call_ma_server( ns_config.ma_server_url[ (ngx.ctx.m_params.uin  % #ns_config.ma_server_url) + 1 ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] set_share_win_bean_data SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] set_share_win_bean_data FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

--! @brief 9号福利发奖
FOO.get_task_reward = function(extra_t, position_id)
	local reason_ = 'business_advert_get_task_reward'
	local time_ = uu.now()
	local info = {
		cmd = 'task_reward',
		task_id = extra_t.task_id,
		randomidx = extra_t.randomidx,
		reason =  reason_,
		uin = ngx.ctx.m_params.uin,
		ts = time_,
	}

	local ret = call_account( ns_config.gm_cost_server_url[ (ngx.ctx.m_params.uin  % #ns_config.ma_server_url) + 1 ], info, time_)
	ret.reward_list = {}
	if ret.errorcode == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] get_task_reward SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
		if ret.return_result and ret.return_result.itemmap and ret.return_result.avatar_skin_to_minibean then 
			ret.reward_list.itemmap = ret.return_result.itemmap
			ret.reward_list.avatar_skin_to_minibean = ret.return_result.avatar_skin_to_minibean
		end
		ret.return_result = nil
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] get_task_reward FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	ret.ret = ret.errorcode
	return ret
end

--! @brief 复活奖励
FOO.revive_ad_reward = function(extra_t, position_id)
	local reason_ = 'business_advert_revive_ad_reward'
	local time_ = uu.now()
	local info = {
		act = 'revive_ad_reward',
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver or "1.6.0",
		apiid = ngx.ctx.m_params.apiid or 999,
		ad_id = position_id,
		survival = extra_t.survival or 0,
	}

	local ret = call_business_server( ns_config.business_server_url[ (ngx.ctx.m_params.uin  % #ns_config.business_server_url) + 1  ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] revive_ad_reward SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] revive_ad_reward FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

--! @brief 幸运方块
FOO.lucky_block = function(extra_t, position_id)
	local act_name = ""
	if position_id==32 then 
		act_name = "lucky_block_enter"
	elseif position_id==33 then 
		act_name = "lucky_block_delete_monkey"
	end	

	local reason_ = "business_advert_" .. act_name
	local time_ = uu.now()
	local info = {
		act = act_name,
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver,
		apiid = ngx.ctx.m_params.apiid,
		type = extra_t.type,
	}

	local ret = call_business_welfare_server( ns_config.business_welfare_server_url[ (ngx.ctx.m_params.uin  % #ns_config.business_welfare_server_url) + 1  ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] "..act_name.. " SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] "..act_name.. " FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

--! @brief 30广告商人2兑换物品
FOO.purchase_goods = function(extra_t, position_id)
	local reason_ = 'business_advert_purchase_goods'
	local time_ = uu.now()
	local info = {
		act = 'purchase_goods',
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver,
		apiid = ngx.ctx.m_params.apiid,
		--params
		itemid     = tonumber(extra_t.itemid),
		itemnum    = tonumber(extra_t.itemnum),
 		iswarehouse = tonumber(extra_t.iswarehouse),
 		pricetype  = tonumber(extra_t.pricetype),
	 	price   = tonumber(extra_t.price),
	}

	local ret = call_business_server( ns_config.business_server_url[ (ngx.ctx.m_params.uin  % #ns_config.business_server_url) + 1  ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] purchase_goods SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] purchase_goods FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

--! @brief 29悦享卡广告
FOO.get_task_experience = function(extra_t, position_id)
	local reason_ = 'business_advert_get_task_experience'
	local time_ = uu.now()
	local info = {
		act = 'get_task_experience',
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver,
		apiid = ngx.ctx.m_params.apiid,
		--params
		taskid     = extra_t.taskid,
		value    = extra_t.value,
		adid = extra_t.adid,
		groupid = extra_t.groupid,
		grouptype = extra_t.grouptype

	}

	local ret = call_battlepass( ns_config.battlepass_server_url[ (ngx.ctx.m_params.uin  % #ns_config.battlepass_server_url) + 1  ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] get_task_experience SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] get_task_experience FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

--! @brief 36号迷你点收益
FOO.get_accumulate_reward = function(extra_t, position_id)
	local reason_ = "business_advert_get_accumulate_reward"
	local time_ = uu.now()
	local info = {
		act = "get_accumulate_reward",
		uin = ngx.ctx.m_params.uin,
		time = time_,
		ver = ngx.ctx.m_params.ver,
		apiid = ngx.ctx.m_params.apiid,
		--params
		tag = extra_t.tag or 1,
		reward_type = extra_t.reward_type or 2,
	}

	local ret = call_business_welfare_server( ns_config.business_welfare_server_url[ (ngx.ctx.m_params.uin  % #ns_config.business_welfare_server_url) + 1  ], info, time_)
	if ret.ret == 0 then
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] ".."get_accumulate_reward".. " SUCCESS"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	else
		log.day_list(ADVERT_REWARDS, ('[position_id:'.. (position_id or "nil") .. "] ".."get_accumulate_reward".. " FAILURE"), ngx.ctx.m_params.uin, reason_, uu.table2json(ret), time_)
	end

	return ret
end

return FOO
